import java.io.*;
import java.net.*;
public class TCServerThread extends Thread {
	public Socket client;
	public OutputStream out;
	public InputStream in;
	
	public String colseConnection;
	public String receiverData;
	public TCServerThread (Socket client){
		this.client = client;
		try{
			out = client.getOutputStream();
		}catch(IOException e){
		}
	}
	public boolean sendString (String msg){
		byte[] data = msg.getBytes();
		try {
			out.write(data);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public String getString (){
		String Msg = null;
		try {
			in = client.getInputStream();
			StringBuffer stb = new StringBuffer();
			int data = 0;
			int Exit = 13;
			while(data != Exit ){
				data = in.read();
				if(data == -1){
					client.close();
					break;
				}
				stb.append((char)data);

			}
			Msg = stb.toString().trim();
		} catch (IOException e) {
			Msg = "fail";
		}
		return Msg;
	}
	public void taskProcess (){
		String clientMsg = "";
		String Exit = "bye";
		String reMsg= "Success\r";
		String testMsg = "are you ok";
		String endMsg = "end";
		int endFlag = 1;
		TCSerial tcs = new TCSerial();
		String sys_Batch = tcs.getBatch();
		int i = 1;
		clientMsg = getString();
		while(!clientMsg.equals(Exit)){
			if(clientMsg.equals(testMsg)){
				sendString("ok\r");
			}else if(clientMsg.matches("[0-9]{4}-[0-9]{2}-[0-9]{2},[0-9]{1,4},[0-9]{1,4},[0-9]{5},[0-9]{1,9}.[0-9]{2},(Refundment|Deposit)")){
				TCDatabase tcdatabase = new TCDatabase();
				if(tcdatabase.insertInfo(clientMsg,sys_Batch, i)){
					sendString(reMsg);
				}else{
					sendString("fail\r");
					break;
				};
				i++;
			}else if(clientMsg.matches(endMsg)){
				TCExeShell tces = new TCExeShell();
				tces.exeShell();
				sendString(reMsg);
				endFlag = 0;
				break;
			}else{
				break;
			}
			clientMsg = getString();
		
		}
		tcs.setBatch();
		if(!client.isClosed()){
			try {
				out.close();
				in.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
	public void run(){
		taskProcess();
	
	}

}
